'use strict'

const moment = require('moment');
const Service = require('egg').Service

class ChatService extends Service {
  // 登录
  async login({ third_id, app_id }) {
    let sql = `select * from t_user where (app_id = ? and third_id = ?)`;
    const record = await this.app.mysql.query(sql, [`${app_id}`, `${third_id}`]);
    if (!record.length) {
      const sql = `insert into t_user (app_id, third_id) values (?, ?)`;
      const record = await this.app.mysql.query(sql, [`${app_id}`, `${third_id}`]);
      if (record.affectedRows === 1) {
        const record = await this.app.mysql.query(sql, [`${app_id}`, `${third_id}`]);
        return record[0];
      }
    }
    return record[0];
  }

  /**
   * 获取聊天列表
   * @param {*} param0 
   */
   async getChatList2({ user_id }) {
    /**
     * 私发消息
     */
    let sql = `
      select
        t_user.nickname,
        t_user.avatar,
        partner_id
      from
        (
          select
            *,   
            case when s_user=${user_id} then r_user else s_user end as partner_id
          from
            t_msg
          where
            (t_msg.s_user = ${user_id} or t_msg.r_user = ${user_id})
          and
            t_msg.is_group = 0
          group by
            partner_id
        ) g
      left join
        t_user
      on
        t_user.id = g.partner_id
    `
    let record = await this.app.mysql.query(sql);

    let roomGroup = await this.app.mysql.query(`
      select
        s.is_group,
        room.room_name as nickname,
        room.room_icon as avatar,
        room.room_key as partner_id
      from
        (
          select
            *
          from t_msg
            where t_msg.s_user = ${user_id} and t_msg.is_group = 1
          group by
            room_id
        ) s
      left join
        t_chat_room room
      on
        room.room_key = s.room_id
    `);
    roomGroup = JSON.parse(JSON.stringify(roomGroup));
    return {
      retCode: '0',
      errCode: '0',
      errMsg: '',
      data: {
        list: record.concat(roomGroup)
      }
    }
  }

  async getMsgFromPartner(userId, partnerId, isGroup) {
    if (!isGroup) {
      const sql = `
        select *
        from t_msg
        where
          (t_msg.s_user = ${partnerId} and t_msg.r_user = ${userId}) or
          (t_msg.s_user = ${userId} and t_msg.r_user = ${partnerId})
      `
      return await this.app.mysql.query(sql);
    } else {
      const sql = `
        select *
        from t_msg
        where t_msg.room_id = '${partnerId}'
      `
      return await this.app.mysql.query(sql);
    }
  }

  /**
   * 获取聊天列表
   * @param {*} param0 
   */
  async getChatList({ user_id }) {
    const sql = `
      select
        s.partner_id,
        t_user.id,
        t_user.nickname,
        t_user.avatar,
        t_msg.content,
        t_msg.type,
        t_msg.create_time
      from
        (
          select
            *,
            max(id) as last_id
          from
            (
              select *,   
                case
                  when s_user=${user_id} then r_user
                  else s_user
                end as partner_id
              from
                t_msg
              where
                (t_msg.s_user = ${user_id} or t_msg.r_user = ${user_id})
              and
                t_msg.is_group = 0
            ) t
          group by partner_id
        ) s
      left join
        t_user
      on
        t_user.id = s.partner_id
      left join
        t_msg
      on
        t_msg.id = s.last_id
    `;
    let record = await this.app.mysql.query(sql);

    // 这里有 BUG
    const sql2 = `
      select
        s.room_id,
        s.room_id as partner_id,
        room.id,
        room.room_name as nickname,
        room.room_icon as avatar,
        t_msg.content,
        t_msg.type,
        t_msg.create_time,
        t_msg.is_group,
        t_user.nickname as user_nickname
      from
        (
          select
            *,
            max(id) as last_id
          from
            (
              select
                *
              from
                t_msg
              where
                t_msg.s_user = ${user_id}
              and
                t_msg.is_group = 1
            ) t
          group by
            room_id
        ) s
      left join
        t_chat_room room
      on
        room.room_key = s.room_id
      left join
        t_msg
      on
        t_msg.id = s.last_id
      left join
        t_user
      on
        t_user.id = s.s_user
    `;

    let roomGroup = await this.app.mysql.query(`
      select *
      from
        (
          select *, max(id) as last_id
          from t_msg
          where t_msg.s_user = 1
          and t_msg.is_group = 1
          group by
          room_id
        ) s
      left join t_chat_room room
      on room.room_key = s.room_id
    `);
    roomGroup = JSON.parse(JSON.stringify(roomGroup));

    roomGroup.forEach(element => {
      element.avatar = element.room_icon;
      element.nickname = element.room_name;
      element.partner_id = element.room_key;
    });

    let sql3 = `
      select *
      from t_msg
      where t_msg.room_id in (${roomGroup.map(el => el.room)})
    `
    
    let record2 = await this.app.mysql.query(sql2);

    return {
      retCode: '0',
      errCode: '0',
      errMsg: '',
      data: {
        list: record.concat(record2),
        roomGroup
      }
    }
  }

  /**
   * 获取与指定用户的历史消息
   * @param {*} param0 
   */
  async getHistory({ s_user, r_user, room_id, is_group, pageIndex, pageSize }) {
    if (is_group != 1) {
      const sql = `
        select
          t.*,
          t_user.nickname,
          t_user.avatar
        from
          (
            select
              *
            from
              t_msg
            where
              (s_user = ${s_user} and r_user = ${r_user})
            or
              (r_user = ${s_user} and s_user = ${r_user})
            order by
              create_time DESC
            limit
              ${pageSize}
            offset
              ${(pageIndex - 1) * pageSize}
          ) t
        left join
          t_user 
        on
          t_user.id = t.s_user
      `;
      let record = await this.app.mysql.query(sql);
      record = JSON.parse(JSON.stringify(record));
      const sort = (a, b) => {
        if (a.create_time - b.create_time) return 0
        return a.create_time > b.create_time ? 1 : -1
      }
      record.sort(sort);
      return {
        data: {
          list: record
        }
      }
    } else {
      const sql = `
        select
          t.*,
          t_user.nickname,
          t_user.avatar
        from
          (
            select
              *
            from
              t_msg
            where
              room_id = '${room_id}'
            order by
              create_time DESC
            limit
              ${pageSize}
            offset
              ${(pageIndex - 1) * pageSize}
          ) t
        left join
          t_user 
        on
          t_user.id = t.s_user
      `;
      let record = await this.app.mysql.query(sql);
      record = JSON.parse(JSON.stringify(record));
      const sort = (a, b) => {
        if (a.create_time - b.create_time) return 0
        return a.create_time > b.create_time ? 1 : -1
      }
      record.sort(sort);
      return {
        data: {
          list: record
        }
      }
    }
  }

  /**
   * 获取用户信息
   * @param {*} param0 
   */
  async getUserInfo({ user_id }) {
    let sql = `select * from t_user where id = ${user_id}`;
    let result = await this.app.mysql.query(sql)
    return result[0];
  }

  /**
   * 获取与指定用户的聊天列表
   * @param {*} param0 
   */
  async show({ uid, partnerId }) {
    let result = await this.app.mysql.select('chat', {
      where: {
        f_from: [uid, partnerId],
        f_to: [uid, partnerId]
      }
    })

    const msgList = JSON.parse(JSON.stringify(result))
    const partnerInfo = await this.app.mysql.get('user', {
      id: partnerId
    })

    return {
      retCode: '0',
      errCode: '0',
      errMsg: '',
      data: {
        msgList: msgList,
        partnerInfo: partnerInfo
      }
    }
  }

  /**
   * 发送消息
   * @param {*} param0 
   */
  async create({
    s_user,
    r_user,
    content,
    room_id,
    is_group,
    avatar,
    nickname
  }) {
    const values = {
      s_user,
      r_user,
      content,
      type: 0,
      is_read: 0,
      avatar,
      nickname,
      room_id: room_id || null,
      is_group: is_group || 0,
      create_time: Date.now()
    }
    await this.app.mysql.insert('t_msg', values);
    return values;
  }

  /**
   * 用户搜索
   * 添加好友时会被用到
   * @param {*} param0 
   */
  async searchUser({ searchKey }) {
    const sql = `select * from t_user u where u.nickname LIKE '%${searchKey}%'`;
    return await this.app.mysql.query(sql);
  }
}

module.exports = ChatService
